#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@Introduce :
@File      : comm.py
@Time      : 2021/4/9 16:26
@Author    : toby
"""



import configparser,os
# from db.mydb import *
import re

import openpyxl
from openpyxl import Workbook

import pandas as pd
import logging

logger = logging.getLogger(__name__)

class Comm():

    def read_data(self,filepath,sheet_name=None):
        '''
        读取excel文件
        :param filepath: 文件路径
        :return:
        '''
        logger.info("------- start read data-----------")
        df = pd.read_excel(filepath)
        nrows = len(df)
        columnsnum = df.columns.size
        logger.info(nrows, columnsnum)
        logger.info("----------------------nrows,column")

        datalist = []
        for i in range(nrows):
            last = []
            for j in range(0, columnsnum ):
                val = df.iloc[i, j]
                last.append(val)
            datalist.append(last)
        logger.info(datalist)
        return datalist

    # 写excel 到第一个sheet中
    def write_to_excel(self,file_name,row,column,content):
        workbook = openpyxl.load_workbook(file_name)
        # 可以使用workbook对象的sheetnames属性获取到excel文件中哪些表有数据
        ws =  workbook['Sheet3']
        logger.info("准备写入到excel中..")
        for i in range(len(content)):
            ws.cell(row=row,column=column+i).value=content[i]

        workbook.save(filename= file_name)
        print('write_over!')

    def write_to_excel_list(self,file_name,content):
        workbook = openpyxl.load_workbook(file_name)
        # 可以使用workbook对象的sheetnames属性获取到excel文件中哪些表有数据
        sheets = workbook.sheetnames
        print(sheets)
        ws =  workbook['Sheet3']
        logger.info("准备写入到excel中..")
        for i in range(len(content)):
            ws.cell(row=i+1,column=2).value=content[i]

        workbook.save(filename= file_name)
        print('write_over!')


    # 最新文件
    def _last_file(self,dir):
        '''
        查找目录下最新的文件,last file
        '''
        file_lists = os.listdir(dir)
        file_lists.sort(key=lambda fn: os.path.getmtime(dir + "/" + fn))
        print('最新的文件为： ' + file_lists[-1])
        file = os.path.join(dir, file_lists[-1])
        print('完整路径：', file)
        return file,file_lists[-1]



'''
断言模块

'''

class Assertion(object):
    '''
    验证返回信息
    :param return_code:
    :return:
    '''
    def ass_code(self, post, expected):

        if not post is None:
            try:
                return_code = re.findall(r'"error": (.+?),', str(post))
                logger.info(return_code)
                assert return_code == expected
                return "验证返回code值与预期值：%s : %s" % (return_code, expected)

            except EnvironmentError as y:
                raise ValueError("接口内容没有返回！code值", y)
        else:
            return "接口请求的返回值为空！code"

    def ass_message(self, post, expected):
        '''
        验证返回信息
        :param return_message:
        :return:
        '''
        if not post is None:
            try:
                return_message = re.findall(r'"message": (.+?),', str(post))
                if return_message != []:
                    assert return_message[0] == expected
                    return "验证返回message值与预期值：%s : %s" % (return_message[0], expected)
                else:
                    print("message值为空！")

            except EnvironmentError as y:
                raise ValueError("接口内容没有返回！message值", y)
        else:
            return "接口请求的返回值为空！message"



if __name__ == '__main__':

    Comm().read_data(('/root/flask-celery-hjw/flask-celery/pytest_pkg/testcase-data/白名单站点月卡接口测试用例.xlsx'))
    # data = ReadExcel('D:/flask-celery-py3/pytest_pkg/testcase-data/白名单站点月卡接口测试用例.xlsx').read('Sheet')
    # print(data)
    # for i in data :
    #     print(i)





